import json

from django.http import JsonResponse
from django.views import View

from ihome.utils.fastdfs.fastdfs_storage import FastDFSStorage
from ihome.utils.views import LoginRequiredMixin


import re
import logging
logger = logging.getLogger('django')
from wangziye.models import User, Order




#个人中心
class UserInfoView (LoginRequiredMixin, View):
    '''用户中心'''
    def get(self, request):
        '''提供个人信息界面'''
        #获取界面需要的数据,进行凭拼接
        user = User.objects.get(id = request.user.id)
        file_id = user.avatar
        fdfs = FastDFSStorage()  # 创一个fdfs的对象
        avatar_url = fdfs.url(str(file_id))  # 用.url方法拼接路径
        data = {
            'avatar': avatar_url,
            'create_time': user.last_login,
            'mobile': user.mobile,
            'name': user.username,
            'user_id': user.id
        }

        #返回响应
        return JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': '0'
        })





#用户名修改
class ChangeUsernameView(LoginRequiredMixin, View):
    '''用户名修改'''
    def put(self, request):
        #1.接收参数
        dict = json.loads(request.body.decode())
        name = dict.get('name')
        #2.校验参数
        if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5]+$', name):
            return JsonResponse({
                'errno': '4004',
                'errmsg': 'name格式有误'
             })

        #3.修改用户名
        try:
            User.objects.filter(id = request.user.id).update(
                username = name
            )
        #4.判断用户名是否存在,并更新用户名
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'errno': '4003',
                'errmsg': '更新用户名失败'
            })

        # 更新地址结果
        return JsonResponse({
            'errno': '0',
            'errmsg': '修改成功'
        })





#评价订单
class EvaluationOrderView (View):

    def put(self, request, order_id):
        #1.接收参数
        dict = json.loads(request.body.decode())
        comment = dict.get('comment')

        #2.根据id和状态查找到对象,并修改comment 和status,并保存
        try:
            order = Order.objects.get(id = order_id,status = 3)
            order.comment = comment
            order.status = 4
            order.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'errno': '4003',
                'errmsg': '添加评论失败'
            })

        # 3.返回参数
        return JsonResponse({
            'errno': '0',
            'errmsg': '评论成功'
        })














